package com.nebula.controller.management;

import com.alibaba.fastjson.JSON;
import com.nebula.common.Const;
import com.nebula.common.PageResult;
import com.nebula.controller.BaseController;
import com.nebula.entity.Role;
import com.nebula.common.Result;
import com.nebula.service.IRoleService;
import com.nebula.service.IUserService;
import com.nebula.service.impl.RoleServiceImpl;
import com.nebula.service.impl.UserServiceImpl;
import com.nebula.vo.RoleVo;
import com.nebula.vo.UserVo;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author CcccX
 */
@WebServlet(name = "RoleController", urlPatterns = "/manage/role")
public class RoleController extends BaseController {
    private final IUserService userService = new UserServiceImpl();

    private final IRoleService roleService = new RoleServiceImpl();

    public String index(HttpServletRequest request, HttpServletResponse response) {
        String navId = request.getParameter("id");
        UserVo user = (UserVo) request.getSession().getAttribute(Const.USER_INFO);
        if (userService.checkNavRole(user.getRoleId(), navId)) {
            return Const.FORWARD + Const.DEFAULT_URL + "website/role-group.jsp";
        } else {
            return Const.FORWARD + "role-error.jsp";
        }
    }

    public String findByPage(HttpServletRequest request, HttpServletResponse response) {
        String page = request.getParameter("page");
        String rows = request.getParameter("rows");
        UserVo user = (UserVo) request.getSession().getAttribute(Const.USER_INFO);
        if (StringUtils.isBlank(page)) {
            page = Const.PAGE;
        }
        if (StringUtils.isBlank(rows)) {
            rows = Const.SIZE;
        }
        PageResult<RoleVo> pageResult = roleService.findByPage(Integer.parseInt(page), Integer.parseInt(rows),
                user.getRoleId());
        Map<String, Object> map = new HashMap<>();
        map.put("total", pageResult.getTotalCount());
        map.put("rows", pageResult.getList());
        return Const.JSON + JSON.toJSONString(map);
    }

    public String findById(HttpServletRequest request, HttpServletResponse response) {
        String roleId = request.getParameter("id");
        if (StringUtils.isBlank(roleId)) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("角色ID不能为空"));
        }
        Role role = roleService.findById(Integer.parseInt(roleId));
        return Const.JSON + JSON.toJSONString(Result.createBySuccess(role));
    }

    public String findAll(HttpServletRequest request, HttpServletResponse response) {
        List<RoleVo> roleVos = roleService.findAll();
        return Const.JSON + JSON.toJSONString(Result.createBySuccess(roleVos));
    }

    public String findByNavId(HttpServletRequest request, HttpServletResponse response) {
        String navId = request.getParameter("navId");
        if (StringUtils.isBlank(navId)) {
            return null;
        }
        //查询该菜单所属角色组
        Map<String, Object> map = roleService.selectRoleIdByNavIdFromRoleNavigation(navId);
        return Const.JSON + JSON.toJSONString(map);
    }

    public String save(HttpServletRequest request, HttpServletResponse response) {
        UserVo user = (UserVo) request.getSession().getAttribute(Const.USER_INFO);
        try {
            String desc = request.getParameter("desc");
            String roleName = request.getParameter("role");
            String roleLevel = request.getParameter("roleLevel");
            if (StringUtils.isBlank(desc) || StringUtils.isBlank(roleName) || StringUtils.isBlank(roleLevel)) {
                return null;
            }
            Role role = new Role();
            role.setRole(roleName);
            role.setInstruction(desc);
            role.setRoleLevel(Integer.parseInt(roleLevel));
            role.setUser(user.getUsername());
            role.setUserRole(roleService.findById(user.getRoleId()).getRole());
            Date date = new Date();
            role.setCreatedTime(date);
            role.setUpdatedTime(date);
            roleService.save(role);
            return Const.JSON + JSON.toJSONString(Result.createBySuccessMessage("添加成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("添加失败"));
        }
    }

    public String update(HttpServletRequest request, HttpServletResponse response) {
        String roleName = request.getParameter("role");
        String desc = request.getParameter("desc");
        String roleLevel = request.getParameter("roleLevel");
        String roleId = request.getParameter("roleId");

        if (StringUtils.isBlank(roleId)) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("角色ID不能为空"));
        }
        if (StringUtils.isBlank(roleName)) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("角色名称不能为空"));
        }
        if (StringUtils.isBlank(desc)) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("角色描述不能为空"));
        }

        Role role = new Role();
        role.setRole(roleName);
        role.setId(Integer.parseInt(roleId));
        role.setInstruction(desc);
        role.setRoleLevel(Integer.parseInt(roleLevel));
        try {
            roleService.update(role);
            return Const.JSON + JSON.toJSONString(Result.createBySuccessMessage("修改成功"));
        } catch (Exception e) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("修改失败"));
        }
    }

    public String delete(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        if (StringUtils.isBlank(id)) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("角色ID不能为空"));
        }

        int resultCount = roleService.delete(Integer.parseInt(id));
        if (resultCount > 0) {
            return Const.JSON + JSON.toJSONString(Result.createBySuccessMessage("删除成功"));
        } else {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("删除失败"));
        }
    }
}
